package com.speridian.oms.view.beans.backing;


import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.FontFactoryImp;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;


import com.speridian.oms.view.beans.login.Login;
import com.speridian.oms.view.beans.pojo.AssetInfo;

import com.speridian.oms.view.beans.utils.ADFUtils;

import com.speridian.oms.view.beans.utils.JSFUtils;
import com.speridian.oms.view.beans.utils.JSFUtils;

import com.speridian.oms.view.beans.utils.MessageUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.math.BigDecimal;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.el.ExpressionFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import javax.faces.validator.ValidatorException;

import javax.servlet.http.HttpServletResponse;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceRef;

import oracle.adf.controller.internal.binding.DCTaskFlowBinding;
import oracle.adf.model.BindingContext;
import oracle.adf.model.RegionContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCDataControl;
import oracle.adf.model.binding.DCIteratorBinding;

import oracle.adf.view.rich.component.rich.input.RichInputDate;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;
import oracle.adf.view.rich.component.rich.layout.RichPanelHeader;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;


import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.binding.BindingContainer;

import oracle.binding.OperationBinding;

import oracle.jbo.Row;
import oracle.jbo.ViewObject;
import oracle.jbo.domain.BlobDomain;
import oracle.jbo.server.ViewObjectImpl;

import org.apache.commons.io.IOUtils;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;


import po.PurchaseOrderBPEL;
import po.Purchaseorderbpel_client_ep;

import po.types.HeaderType;

import po.types.POAssetType;

import po.types.PurchaseOrderRequest;

import po.types.PurchaseOrderResponse;

import sun.font.FontFamily;

public class PurchaseOrderBackingBean {

    private List<AssetInfo> assetInfo;
    private List<SelectItem> vendorList;
    private List<SelectItem> itemList;
    private List<SelectItem> addressList;
    private List<SelectItem> locationList;
    private List<SelectItem> systemList;
    private String result;
    private String masterLocation;
    private String fileName;
    private int assetCount = 0;
    int count;
    private static String RESULT;


    @WebServiceRef
    Purchaseorderbpel_client_ep pce = new Purchaseorderbpel_client_ep();
    private RichPanelHeader purchaseOrderFormBinding;
    private RichPanelFormLayout poGeneralFormBinding;
    private RichInputText totalAmountBinding;
    private RichInputDate releaseDateBinding;
    private RichInputText termsBinding;
    private RichInputDate createdDateBinding;
    private RichInputText approvedByBinding;

    public PurchaseOrderBackingBean() {
        super();
        assetInfo = new ArrayList<AssetInfo>();
        AssetInfo laptop = new AssetInfo();
        assetInfo.add(laptop);
        vendorList = new ArrayList<SelectItem>();
        assetCount++;
        count = 1;
    }


    public void setAssetCount(int assetCount) {
        this.assetCount = assetCount;
    }

    public int getAssetCount() {
        return assetCount;
    }

    public void setassetInfo(List<AssetInfo> assetInfo) {
        this.assetInfo = assetInfo;
    }

    public List<AssetInfo> getassetInfo() {
        return assetInfo;
    }

    public String AddAsset() {
        AssetInfo laptop = new AssetInfo();
        assetInfo.add(laptop);
        assetCount++;
        return null;
    }


    public String removeAsset() {
        Object uuid =
            JSFUtils.resolveExpression("#{requestScope.pLaptopRemove}");
        if (uuid != null) {
            if (assetCount != 1) {
                for (AssetInfo li : assetInfo) {
                    if (uuid.equals(li.getUuid())) {
                        assetInfo.remove(li);
                        assetCount--;
                        return null;
                    }
                }
            } else {
                MessageUtils.displayMessage(null,
                                            "Sorry cannot delete. Atleast one asset needed");
            }
        }
        return null;
    }


    public void setVendorList(List<SelectItem> vendorList) {
        this.vendorList = vendorList;
    }

    public List<SelectItem> getVendorList() {
        vendorList = new ArrayList<SelectItem>();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstVendorVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.removeApplyViewCriteriaName("OmMstVendorVOCriteria");
        vo.executeQuery();
        int i = 0;
        if (vo.hasNext()) {
            i++;
            Row row = vo.first();
            Object vendorName = row.getAttribute("Vendorname");
            vendorList.add(new SelectItem(i, vendorName.toString()));
        }
        while (vo.hasNext()) {
            vo.next();
            i++;
            Object vendorName = vo.getCurrentRow().getAttribute("Vendorname");
            vendorList.add(new SelectItem(i, vendorName.toString()));
        }

        return vendorList;
    }

    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public void setItemList(List<SelectItem> itemList) {
        this.itemList = itemList;
    }

    public List<SelectItem> getItemList() {
        itemList = new ArrayList<SelectItem>();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstItemVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.executeQuery();
        if (vo.hasNext()) {
            Row row = vo.first();
            Object itemName = row.getAttribute("Itemtype");
            itemList.add(new SelectItem(Integer.parseInt(row.getAttribute("Itemid").toString()),
                                        itemName.toString()));
        }
        while (vo.hasNext()) {
            vo.next();
            Object itemName = vo.getCurrentRow().getAttribute("Itemtype");
            itemList.add(new SelectItem(Integer.parseInt(vo.getCurrentRow().getAttribute("Itemid").toString()),
                                        itemName.toString()));
        }

        return itemList;
    }

    public void setAddressList(List<SelectItem> addressList) {
        this.addressList = addressList;
    }

    public static DCBindingContainer getBinding() {

        FacesContext fctx = FacesContext.getCurrentInstance();
        ExpressionFactory exp = fctx.getApplication().getExpressionFactory();
        return (DCBindingContainer)exp.createValueExpression(fctx.getELContext(),
                                                             "#{bindings}",
                                                             DCBindingContainer.class).getValue(fctx.getELContext());

    }

    public List<SelectItem> getAddressList() {
        addressList = new ArrayList<SelectItem>();

        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstAddressVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.removeApplyViewCriteriaName("OmMstAddressVOCriteria");
        vo.executeQuery();
        //        DCBindingContainer bc = getBinding();
        //        DCIteratorBinding iteratorBindings =
        //                       (DCIteratorBinding)bc.get("OmMstAddressVO1Iterator");
        //               ViewObject  vo = iteratorBindings.getViewObject();

        if (vo.hasNext()) {
            Row row = vo.first();
            Object address = row.getAttribute("Address");
            addressList.add(new SelectItem(Integer.parseInt(row.getAttribute("AId").toString()),
                                           address.toString()));
        }
        while (vo.hasNext()) {
            vo.next();
            Object address = vo.getCurrentRow().getAttribute("Address");
            addressList.add(new SelectItem(Integer.parseInt(vo.getCurrentRow().getAttribute("AId").toString()),
                                           address.toString()));
        }
        
        return addressList;
    }

    public String saveToPdfAndService() throws IOException, DocumentException,
                                               ParseException,
                                               DatatypeConfigurationException,
                                               InterruptedException {
        createPdf();
        return null;
    }

    //Return address from LOV

    public String returnAddress(String address) {
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator1 =
            dcBindings.findIteratorBinding("OmMstAddressVO1Iterator");
        ViewObjectImpl vo1 = (ViewObjectImpl)iterator1.getViewObject();
        vo1.setApplyViewCriteriaName("OmMstAddressVOCriteria");
        vo1.setNamedWhereClauseParam("pAddressId", address);
        vo1.executeQuery();
        String addressValue = vo1.first().getAttribute("Address").toString();
        Object location = vo1.first().getAttribute("Location");
        setMasterLocation(location.toString());
        return addressValue;
    }

    public XMLGregorianCalendar returnDate(String dateString) throws ParseException,
                                                                     DatatypeConfigurationException {
        Date date = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        date = df.parse(dateString);
        GregorianCalendar cal1 = new GregorianCalendar();
        cal1.setTime(date);

        XMLGregorianCalendar xmlDate2 =
            DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal1.get(Calendar.YEAR),
                                                                      cal1.get(Calendar.MONTH) +
                                                                      1,
                                                                      cal1.get(Calendar.DAY_OF_MONTH),
                                                                      DatatypeConstants.FIELD_UNDEFINED);
        return xmlDate2;
    }

    public String newRow(String date) {
        DCBindingContainer bindings =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        OperationBinding operationBinding =
            bindings.getOperationBinding("CreateInsert");
        Object result = operationBinding.execute();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmPoNumberVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        Object poNumber = vo.getCurrentRow().getAttribute("PoNumber");
        vo.getCurrentRow().setAttribute("PoDate", date);
        OperationBinding operationBinding1 =
            bindings.getOperationBinding("Commit");
        operationBinding1.execute();
        if (operationBinding.getErrors().isEmpty()) {
            System.out.println("No errors");
        }
        return poNumber.toString();
    }

    public void createPdf() throws IOException, DocumentException,
                                   ParseException,
                                   DatatypeConfigurationException,
                                   InterruptedException {

        //Variable declaration
        boolean isPass = true;

        //Retrieving value from front end
        Object created_By =
            JSFUtils.resolveExpression("#{sessionScope.UserSession.userFullname}");
        Object b_Address =
            JSFUtils.resolveExpression("#{pageFlowScope.b_Address}");
        Object c_Date = JSFUtils.resolveExpression("#{pageFlowScope.c_Date}");
        Object S_location =
            JSFUtils.resolveExpression("#{pageFlowScope.S_location}");
        Object rel_date =
            JSFUtils.resolveExpression("#{pageFlowScope.rel_date}");
        Object v_name = JSFUtils.resolveExpression("#{pageFlowScope.v_name}");
        Object req_To = JSFUtils.resolveExpression("#{pageFlowScope.req_To}");
        Object appr_By =
            JSFUtils.resolveExpression("#{pageFlowScope.appr_By}");
        Object terms = JSFUtils.resolveExpression("#{pageFlowScope.terms}");
        Object t_amt = JSFUtils.resolveExpression("#{pageFlowScope.t_Amt}");


        //Validation of front end values
        //        if (created_By == null) {
        //            MessageUtils.displayErrorMessage(null,
        //                                             "Created By cannot be null");
        //            isPass = false;
        //        }
        if (t_amt == null || t_amt.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Total Amount cannot be null");
            isPass = false;
        }
        if (b_Address == null || b_Address.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Billing Address cannot be null");
            isPass = false;
        }
        if (c_Date == null || c_Date.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Created Date cannot be null");
            isPass = false;
        }
        if (S_location == null || S_location.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Shipment Location cannot be null");
            isPass = false;
        }
        if (rel_date == null || rel_date.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Release date cannot be null");
            isPass = false;
        }
        if (v_name == null || v_name.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Vendor name cannot be null");
            isPass = false;
        }
        if (req_To == null || req_To.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Requested to cannot be null");
            isPass = false;
        }
        if (appr_By == null || appr_By.equals("")) {
            MessageUtils.displayErrorMessage(null,
                                             "Approved By cannot be null");
            isPass = false;
        }
        if (terms == null || terms.equals("")) {
            MessageUtils.displayErrorMessage(null, "Terms cannot be null");
            isPass = false;
        }
        int i = 0;


        //validation of pojo class values of front end attributes
        for (AssetInfo li : assetInfo) {
            i++;
            Object category = li.getCategory();
            if (category == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Category cannot be null");
                isPass = false;
            } else if (category.equals("System")) {
                if (li.getMemory() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Memory cannot be null");
                    isPass = false;
                }
                if (li.getSize() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Display Size cannot be null");
                    isPass = false;
                }
                if (li.getProcessor() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Processor cannot be null");
                    isPass = false;
                }
                if (li.getHd() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Hard Disk cannot be null");
                    isPass = false;
                }
            }
            if (li.getModel() == null) {
                MessageUtils.displayErrorMessage(null, "Model cannot be null");
                isPass = false;
            }
            if (li.getBrand() == null) {
                MessageUtils.displayErrorMessage(null, "Brand cannot be null");
                isPass = false;
            }
            if (li.getType() == null) {
                MessageUtils.displayErrorMessage(null, "Type cannot be null");
                isPass = false;
            }
            if (li.getRate() == null) {
                MessageUtils.displayErrorMessage(null, "Rate cannot be null");
                isPass = false;
            }
            if (li.getAdd_req() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Additional requirement cannot be null");
                isPass = false;
            }
            if (li.getQty() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Quantity cannot be null");
                isPass = false;
            }
            if (li.getAmount() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Amount cannot be null");
                isPass = false;
            }
            if (li.getRemark() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Remark cannot be null");
                isPass = false;
            }
        }
        if (!isPass) {
            return;
        }


        //Retrieving values by reverse LOV process

        //Vendor name
        int vendor_id = Integer.parseInt(v_name.toString());
        if (vendor_id < 10) {
            v_name = "VID_00" + Integer.valueOf(vendor_id);
        } else if (vendor_id < 100) {
            v_name = "VID_0" + Integer.valueOf(vendor_id);
        } else {
            v_name = "VID_" + Integer.valueOf(vendor_id);
        }
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstVendorVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.setApplyViewCriteriaName("OmMstVendorVOCriteria");
        vo.setNamedWhereClauseParam("pVendorId", v_name);
        vo.executeQuery();
        vo.getQuery();
        Object vendor = null;
        Row row = vo.first();
        vendor = row.getAttribute("Vendorname");


        //Address
        String billing_add = returnAddress(b_Address.toString());
        Object s_Address =
            JSFUtils.resolveExpression("#{pageFlowScope.s_Address}");
        String ship_ad = returnAddress(s_Address.toString());
        String mastLocation = getMasterLocation();


        // Passing data to service
        HeaderType ht = new HeaderType();
        ht.setAPPROVEDBY(appr_By.toString());
        ht.setBILLINGADDRESS(billing_add.toString());
        ht.setCREATEDBY(created_By.toString());

        DateFormat formatter =
            new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
        Date date1 = (Date)formatter.parse(c_Date.toString());
        // DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        //Date date1 = (Date)df.parse(c_Date.toString());

        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        String formatedDate1 =
            cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) + 1) +
            "-" + cal1.get(Calendar.DATE);
        XMLGregorianCalendar xmlDate = returnDate(formatedDate1);
        System.out.println("XML Date=" + xmlDate.toString());
        ht.setCREATEDDATE(xmlDate);


        // Date date2 = (Date)df.parse(rel_date.toString());
        Date date2 = (Date)formatter.parse(rel_date.toString());
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date2);
        String formatedDate2 =
            cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) + 1) +
            "-" + cal1.get(Calendar.DATE);


        xmlDate = returnDate(formatedDate2);


        String PONumber = newRow(xmlDate.toString());
        ht.setPURCHASEORDERNUMBER("PO_" + PONumber);
        String poNumberString = mastLocation + PONumber;
        System.out.println("XML Date=" + xmlDate.toString());
        ht.setRELEASEDATE(xmlDate);
        ht.setREQUESTEDTO(req_To.toString());
        ht.setSHIPMENTADDRESS(ship_ad.toString());
        ht.setSHIPMENTLOCATION(S_location.toString());
        ht.setTERMS(terms.toString());
        BigDecimal valDouble =
            new BigDecimal(Integer.parseInt(t_amt.toString()));
        ht.setTOTALAMOUNT(valDouble);
        ht.setVENDORNAME(v_name.toString());
        POAssetType asset = new POAssetType();
        PurchaseOrderRequest request = new PurchaseOrderRequest();
        request.setHeader(ht);
        List assetList = new ArrayList<POAssetType>();
        assetList = request.getPurchaseOrderAsset();
        for (AssetInfo li : assetInfo) {
            i++;
            asset.setItemCategory(li.getCategory());
            if ((li.getCategory().equals("System"))) {
                asset.setItemModel(li.getModel());
                asset.setHardDisk(li.getHd());
                asset.setMemory(li.getMemory());
                asset.setProcessor(li.getProcessor());
                asset.setDisplaySize(li.getSize());
            }
            asset.setAdditionalRequirement(li.getAdd_req());
            valDouble = new BigDecimal(Integer.parseInt(li.getAmount()));
            asset.setAmount(valDouble);
            asset.setBrand(li.getBrand());
            asset.setItemType(li.getType());
            valDouble = new BigDecimal(Integer.parseInt(li.getQty()));
            asset.setQuantity(valDouble);
            valDouble = new BigDecimal(Integer.parseInt(li.getRate()));
            asset.setRate(valDouble);
            asset.setRemarks(li.getRemark());
            assetList.add(asset);
        }


        PurchaseOrderBPEL pob = pce.getPurchaseOrderBPEL_pt();

        PurchaseOrderResponse response = pob.purchaseOrder(request);
        String result = response.getOutcome();
        System.out.println("---------------------------------------" + result +
                           "---------------------------------------");


        //Passing data to service complete

        // PDF creation steps
        if (result.equals("success")) {
            Document document = new Document();
            //        RESULT =
            //               "/home/ADF/Purchase Order" + poNumberString.toString() + ".pdf"; //PDF Path------------------------
            RESULT =
                    "C:/Purchase Order" + poNumberString.toString() + ".pdf"; //PDF Path------------------------
            setResult(RESULT);
            setFileName("PurchaseOrder" + poNumberString + ".pdf");
            PdfWriter.getInstance(document, new FileOutputStream(RESULT));
            document.open();
            Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
            document.add(new Paragraph("                                                        WORK ORDER",
                                       fontbold));
            document.add(new Paragraph("                                                 _______________"));
            document.add(new Paragraph("                                      "));
            document.add(new Paragraph("                                      "));
            document.add(new Paragraph("                                                                                                                           PO No:" +
                                       poNumberString));

            Date date = (Date)formatter.parse(rel_date.toString());
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            String formatedDate =
                cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) +
                "/" + cal.get(Calendar.YEAR);
            System.out.println("formatedDate : " + formatedDate);
            document.add(new Paragraph("                                                                                                                           PO Date:" +
                                       formatedDate));
            document.add(new Paragraph("    "));
            document.add(new Paragraph("To"));
            document.add(new Paragraph("    " + vendor.toString()));
            document.add(new Paragraph("    "));
            document.add(new Paragraph("    "));
            document.add(new Paragraph("Dear Sir,"));
            document.add(new Paragraph("We would like to place the order for the following products:"));
            document.add(new Paragraph("                                      "));
            document.add(new Paragraph("                                      "));

            //Call for adding table content
            document.add(createFirstTable(assetInfo));
            document.add(new Paragraph("    "));
            document.add(new Paragraph("    "));
            PdfPTable table = new PdfPTable(8);
            PdfPCell cell;
            Font heading =
                FontFactory.getFont("Times-Roman", 12, Font.BOLD, BaseColor.RED);
            cell = new PdfPCell(new Phrase("Billing Address", heading));
            cell.setColspan(4);
            cell.setBorder(0);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Shipping Address", heading));
            cell.setColspan(4);
            cell.setBorder(0);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(billing_add));
            cell.setColspan(4);
            cell.setBorder(0);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(ship_ad));
            cell.setColspan(4);
            cell.setBorder(0);
            table.addCell(cell);
            document.add(table);
            document.add(new Paragraph("                                      "));
            document.add(new Paragraph("                                      "));
            document.add(new Paragraph("Kindly arrange to deliver the same at the earliest"));
            document.add(new Paragraph("                                      "));
            document.add(new Paragraph("Thanking you,"));
            document.add(new Paragraph("    "));
            document.add(new Paragraph("                                      "));
            document.add(new Paragraph(appr_By.toString()));
            document.close();
            //resetForm();
            FacesContext context = FacesContext.getCurrentInstance();
            RichCommandButton button =
                (RichCommandButton)JSFUtils.findComponent("consolidatedPreview");
            ExtendedRenderKitService service =
                Service.getRenderKitService(context,
                                            ExtendedRenderKitService.class);
            service.addScript(context,
                              "var popup = AdfPage.PAGE.findComponent(\"" +
                              button.getClientId(context) +
                              "\");AdfActionEvent.queue(popup,true);");

        } else {
            MessageUtils.displayErrorMessage(null,
                                             "Purchase Order not saved.There is an issue with SOA Internal server.Please try after sometime.Sorry for the inconvenience. ");

        }
        if(result.equals("success")){
            resetForm();
        }
       
//        AdfFacesContext.getCurrentInstance().addPartialTarget(purchaseOrderFormBinding);

    }

    public static PdfPTable createFirstTable(List<AssetInfo> assetInfo1) throws DocumentException,
                                                                                FileNotFoundException {

        PdfPTable table = new PdfPTable(11);
        table.setWidthPercentage(100);
        table.setSpacingBefore(0f);
        table.setSpacingAfter(0f);
        PdfPCell cell;
        cell = new PdfPCell(new Phrase("SL.No"));
        cell.setColspan(1);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Description"));
        cell.setColspan(4);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Quantity"));
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Rate"));
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Total Amount"));
        cell.setColspan(2);
        table.addCell(cell);
        int i = 0;
        for (AssetInfo li : assetInfo1) {
            i++;
            cell = new PdfPCell(new Phrase(Integer.toString(i)));
            cell.setColspan(1);
            table.addCell(cell);
            cell =
new PdfPCell(new Phrase(li.getBrand() + " " + li.getType() + " " +
                        li.getModel()));
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(li.getQty()));
            cell.setColspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(li.getRate()));
            cell.setColspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Rs. " + li.getAmount() + " /-"));
            cell.setColspan(2);
            table.addCell(cell);
        }

        cell =
new PdfPCell(new Phrase("                                                                        Total"));
        cell.setColspan(9);
        table.addCell(cell);
        cell =
new PdfPCell(new Phrase("Rs. " + JSFUtils.resolveExpression("#{pageFlowScope.t_Amt}").toString() +
                        " /-"));
        cell.setColspan(2);
        table.addCell(cell);
        return table;
    }


    public void setLocationList(List<SelectItem> locationList) {
        this.locationList = locationList;
    }

    public List<SelectItem> getLocationList() {
        locationList = new ArrayList<SelectItem>();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstLocationVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.executeQuery();
        if (vo.hasNext()) {
            Row row = vo.first();
            Object loc = row.getAttribute("Locationname");
            locationList.add(new SelectItem(Integer.parseInt(row.getAttribute("Locationid").toString()),
                                            loc.toString()));
        }
        while (vo.hasNext()) {
            vo.next();
            Object address = vo.getCurrentRow().getAttribute("Locationname");
            locationList.add(new SelectItem(Integer.parseInt(vo.getCurrentRow().getAttribute("Locationid").toString()),
                                            address.toString()));
        }

        return locationList;
    }


    public void setSystemList(List<SelectItem> systemList) {
        this.systemList = systemList;
    }

    public List<SelectItem> getSystemList() {
        systemList = new ArrayList<SelectItem>();
        Object cat = JSFUtils.resolveExpression("#{item.category}");
        if (cat != null) {
            if (cat.toString().equals("System")) {
                systemList.add(new SelectItem(1, "System"));
                systemList.add(new SelectItem(2, "Laptop"));
            } else {
                systemList.add(new SelectItem(1, "Keyboard"));
                systemList.add(new SelectItem(2, "Mouse"));
            }
        }

        return systemList;
    }


    public void downloadFile(FacesContext facesContext,
                             java.io.OutputStream outputStream) throws IOException,
                                                                       DocumentException,
                                                                       ParseException {
        File file = new File(RESULT);
        FileInputStream fis = new FileInputStream(file);
        IOUtils.copy(fis, outputStream);
        fis.close();
        outputStream.flush();
    }

    public void resetForm() {
        //making general form field back to null-start
        
        JSFUtils.setExpressionValue("#{pageFlowScope.createdBy}", null);
        JSFUtils.setExpressionValue("#{pageFlowScope.b_Address}", null);
        JSFUtils.setExpressionValue("#{pageFlowScope.c_Date}", "");
        JSFUtils.setExpressionValue("#{pageFlowScope.S_location}", null);
        JSFUtils.setExpressionValue("#{pageFlowScope.rel_date}", "");
        JSFUtils.setExpressionValue("#{pageFlowScope.s_Address}", null);
        JSFUtils.setExpressionValue("#{pageFlowScope.v_name}", null);
        JSFUtils.setExpressionValue("#{pageFlowScope.req_To}", "");
        JSFUtils.setExpressionValue("#{pageFlowScope.appr_By}", "");
        JSFUtils.setExpressionValue("#{pageFlowScope.t_Amt}", "");
        JSFUtils.setExpressionValue("#{pageFlowScope.terms}", "");
        releaseDateBinding.resetValue();
        totalAmountBinding.resetValue();
        termsBinding.resetValue();
        createdDateBinding.resetValue();
        //approvedByBinding.resetValue();
        getApprovedByBinding().setValue(null);
        //making general form field back to null-end

        //remove purchase order item-details object by object-start
        int assetLength = assetInfo.size();
        for (int i = 0; i < assetLength; i++) {
            assetInfo.remove(i);
        }

        //remove purchase order item-details object by object-end

        //add object for new form-start
        AssetInfo asset = new AssetInfo();
        assetInfo.add(asset);
        assetCount++;
        //add object for new form-end

        //setting result and filenames to null-start
        setResult(null);
        setFileName(null);
       
        vendorList = new ArrayList<SelectItem>();
        assetCount++;
        count = 1;
        //   setting result and filenames to null-end


    }


    public void setResult(String result) {
        this.result = result;
    }

    public String getResult() {
        return result;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() throws IOException, DocumentException,
                                       ParseException {

        if (count == 1) {

            count++;
        }

        return fileName;
    }

    public void setMasterLocation(String masterLocation) {
        this.masterLocation = masterLocation;
    }

    public String getMasterLocation() {
        return masterLocation;
    }

    public void numberValidator(FacesContext facesContext,
                                UIComponent uIComponent, Object object) {
        if (object != null) {
            String name = object.toString();
            String expression = "^[0-9]*";
            CharSequence inputStr = name;
            Pattern pattern = Pattern.compile(expression);
            Matcher matcher = pattern.matcher(inputStr);
            String msg = "Please enter numeric value";
            if (matcher.matches()) {

            } else {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                              msg, null));
            }
        }
    }

    public void setPurchaseOrderFormBinding(RichPanelHeader purchaseOrderFormBinding) {
        this.purchaseOrderFormBinding = purchaseOrderFormBinding;
    }

    public RichPanelHeader getPurchaseOrderFormBinding() {
        return purchaseOrderFormBinding;
    }

    public void setPoGeneralFormBinding(RichPanelFormLayout poGeneralFormBinding) {
        this.poGeneralFormBinding = poGeneralFormBinding;
    }

    public RichPanelFormLayout getPoGeneralFormBinding() {
        return poGeneralFormBinding;
    }


    public void setPce(Purchaseorderbpel_client_ep pce) {
        this.pce = pce;
    }

    public Purchaseorderbpel_client_ep getPce() {
        return pce;
    }


    public void setTotalAmountBinding(RichInputText totalAmountBinding) {
        this.totalAmountBinding = totalAmountBinding;
    }

    public RichInputText getTotalAmountBinding() {
        return totalAmountBinding;
    }

    public void setReleaseDateBinding(RichInputDate releaseDateBinding) {
        this.releaseDateBinding = releaseDateBinding;
    }

    public RichInputDate getReleaseDateBinding() {
        return releaseDateBinding;
    }

    public void setTermsBinding(RichInputText termsBinding) {
        this.termsBinding = termsBinding;
    }

    public RichInputText getTermsBinding() {
        return termsBinding;
    }

    public void setCreatedDateBinding(RichInputDate createdDateBinding) {
        this.createdDateBinding = createdDateBinding;
    }

    public RichInputDate getCreatedDateBinding() {
        return createdDateBinding;
    }

    public void setApprovedByBinding(RichInputText approvedByBinding) {
        this.approvedByBinding = approvedByBinding;
    }

    public RichInputText getApprovedByBinding() {
        return approvedByBinding;
    }
}
